package com.runfast.waimai.web.controller.Driver_controller;

import cn.jpush.api.push.PushResult;
import com.alibaba.fastjson.JSON;
import com.runfast.paotui.dao.model.*;
import com.runfast.paotui.service.*;
import com.runfast.paotui.task.async.MessagePushTask;
import com.runfast.paotui.utils.JiGuangPushUtil;
import com.runfast.waimai.dao.model.RunfastGoodsSellOutStatus;
import com.runfast.waimai.dao.model.RunfastGoodsSellRecord;
import com.runfast.waimai.dao.model.RunfastTransorder;
import com.runfast.waimai.service.RunfastGoodsSellOutStatusService;
import com.runfast.waimai.service.RunfastGoodsSellRecordService;
import com.runfast.waimai.util.MsgPushUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import sun.applet.Main;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/driver/*")
public class Waimaicountcontroller extends DriverBaseController {
    @Resource
    RunfastShopperService shopperService;
    @Resource
    RunfastGoodsSellRecordService goodsSellRecordService;
    @Resource
    OrderService orderService;
    @Resource
    RunfastGoodsSellOutStatusService goodsSellOutStatusService;
    @Resource
    private AmqpTemplate amqpTemplate; //队列推送
    @Resource
    OrderStatusHistoryService orderStatusHistoryService;
    @Resource
    RunfastCuserService runfastCuserService;
    @Resource
    RunfastAgentbusinessService runfastAgentbusinessService;
    @Resource
    RunfastLoginRecordService runfastLoginRecordService;

    @RequestMapping(value = "waimai", method = RequestMethod.POST)//验证
    public @ResponseBody
    ModelMap waimai(@RequestParam(value = "us", required = false, defaultValue = "1") Integer us, String token,
                    @RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
                    @RequestParam(value = "pagesize", required = false, defaultValue = "10") Integer pagesize) {
        Integer page1 = page * pagesize;
        ModelMap model = new ModelMap();
        Integer cout=0;
        //	Integer cout5=  goodsSellRecordService.findstatusnewmsgcount(page1,pagesize,39);

        if (super.getLoginShopper(token) != null) {
            RunfastShopper runfastShopper = shopperService.get(super.getLoginShopper(token).getId());
            Integer teamid = runfastShopper.getTeamid();//通过骑手信息获得分组ID

            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();

            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(date);
            rightNow.add(Calendar.HOUR, +1);

            Date dt1 = rightNow.getTime();
            RunfastAgentbusiness runfastAgentbusiness=runfastAgentbusinessService.findByid(runfastShopper.getAgentId());
            if(runfastAgentbusiness.getOrderMode()!=2){
            cout = goodsSellRecordService.findstatusnewmsgcount(page1, pagesize, runfastShopper.getAgentId());
            }else {
                 cout=0;
            }


            //       model.put("allrow_1", cout);//新任务

            Integer cout2 = goodsSellRecordService.findstatuscount(runfastShopper.getStatus(), page1, pagesize, runfastShopper.getAgentId(), runfastShopper.getId(), dt1);
            //    model.put("allrow_2", cout2);//骑手抢单成功后，进入待取货,还有状态为1的时候，shopper生成，待取货的单

            Integer cout3 = goodsSellRecordService.findCount(pagesize, page, 5, runfastShopper.getId(), runfastShopper.getAgentId(), null);
            //     model.put("allrow_3", cout3);//骑手从商家取完单 ，待送达单


           /* Integer cout4=goodsSellRecordService.findShopperAndStatusErroCount(runfastShopper.getId());
            model.put("allrow_4", cout4);//异常单*/

            Integer cout5 = goodsSellRecordService.findBookTimecount(runfastShopper.getId(), dt1, runfastShopper.getAgentId());

            //    model.put("allrow_5",cout5); //预定单
            Integer allcount = cout + cout2 + cout3 + cout5;
            model.put("waimaicont", allcount);

        }
        return model;
    }

    @PostMapping("paotui")
    public @ResponseBody
    ModelMap paotui(String token, @RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
                    @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        Integer count1=0;
        ModelMap modelMap = new ModelMap();
        Integer page1 = page * pageSize;
        RunfastAgentbusiness runfastAgentbusiness=runfastAgentbusinessService.findByid(super.getLoginShopper(token).getAgentId());
            if(runfastAgentbusiness.getOrderMode()!=2){
         count1 = orderService.findAgentIdAndStatuscount(super.getLoginShopper(token).getAgentId(), 2, page1, pageSize);}
        else {count1=0;}

        Integer count2 = orderService.findByShopperidAndStatuscount(super.getLoginShopper(token).getId(), 3);

        Integer count3 = orderService.findByShopperidAndStatuscount3(super.getLoginShopper(token).getId(), 5);

        Integer all = count1 + count2 + count3;
        modelMap.put("all", all);

        return modelMap;
    }

    @PostMapping("iscancel")
    public @ResponseBody
    ModelMap iscancel(String token, Integer iscancel, @RequestParam(value = "id", required = false) Integer id) {

        //Integer iscancel;//1:用户提出 2:骑手同意3:不同意；4：系统超时确认
        //id为跑腿定单id
        ModelMap model = new ModelMap();
          //1.同意取消跑腿定单
        //	 1)执行操作转单操作,修改数据
        //	2)通知双方取消订单成功
        //2.拒绝取消订单
        //	1)不做任何操作，通知给用户。

        RunfastShopper sp = super.getLoginShopper(token);
        Order gr = orderService.get(id);

            System.out.println("大爷进来啦"+sp);
            if (sp != null && id != null&&iscancel != null && iscancel == 2) {

                //通过定单号查询跑腿订单情况


                if (gr != null && sp != null) {
                    //同意取消
                    gr.setStatus(Order.Status.CANCELED);
                    gr.setIsCancel(2);//骑手同意取消
                    OrderStatusHistory orderStatusHistory = new OrderStatusHistory();
                    orderStatusHistory.setId(null);
                    orderStatusHistory.setStatus(Order.Status.CANCELED);//状态为5
                    orderStatusHistory.setOrderId(gr.getId());
                    orderStatusHistory.setCreateTime(new Date());
                    orderStatusHistory.setUpdateTime(new Date());
                    orderStatusHistoryService.insertSelective(orderStatusHistory);//已取消

                    orderService.updateByPrimaryKeySelective(gr);
                    //     this.rabbitTemplate.convertAndSend("paotui", JSON.toJSONString(gr)); //保存在队列
                    amqpTemplate.convertAndSend("pt_shopper_order_exchange", "", JSON.toJSONString(gr));
                    model.put("success", true);
                    model.put("msg", "骑手同意取消定单成功!");

                }
            } else if (iscancel == 3) {
                gr.setIsCancel(3);//骑手不同意取消
                orderService.updateByPrimaryKeySelective(gr);


        //        System.out.println("用户"+"骑手"+"*********************************************");

                RunfastCuser runfastCuser1 = runfastCuserService.get(gr.getCuserId());
       //         System.out.println("看看"+runfastCuser1+"bptype"+runfastCuser1.getBptype() );
                List<RunfastLoginRecord> runfastCuser=runfastLoginRecordService.getCuserLoginmsg1(runfastCuser1.getId());

      //          System.out.println("用户"+runfastCuser.get(0).getAlias());
                List<RunfastLoginRecord> shopper=runfastLoginRecordService.getshopperLoginmsg(sp.getId());
       //         System.out.println("骑手"+shopper.get(0).getAlias());
                if (runfastCuser != null  && runfastCuser.get(0).getAlias() != null) {

                    if ( runfastCuser1.getBptype() == 0 && !runfastCuser.get(0).getAlias().isEmpty()) {
             //           System.out.println("用户"+"1这来了"+"*********************************************");
                        //push类型对应的用户标识类型 //bptype 0或空  Android用户  1 i
                        // os用户
                        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String date1 = dateFormat.format(gr.getCreateTime());
                        Map<String, String> parms = new HashMap<>();
                        parms.put("Id", gr.getOrderNo());//订单id
                        parms.put("Content", sp.getName() + "已拒绝订单取消申请");//通过登陸骑手发出拒绝申请
                        parms.put("title", sp.getName() + "拒绝订单取消请求");
                        parms.put("orderCode", gr.getOrderNo());//定单号

                        parms.put("createTime", date1);//下单时间

                        parms.put("sound", "refuse.caf");
                        //          MsgPushUtils.sendtoAndroid("10", parms, sp.getName() + "已拒绝转单申请" + gr.getOrderNo(), sp.getName() + "拒绝转单请求", runfastCuser.getAlias());//发送给安卓iod特定用户
                        JiGuangPushUtil.push(Role.Predefine.CUSTOMER, 600, runfastCuser.get(0).getAlias(), "您的跑腿订单" + gr.getOrderNo() + "骑手拒绝了订单取消请求", parms, null);
                        amqpTemplate.convertAndSend("pt_shopper_order_exchange", "", JSON.toJSONString(gr));

                    } else if (runfastCuser1.getBptype() == 1 ) {
             //           System.out.println("用户"+"2这来了"+"*********************************************");

                        //Bptype 0或空  Android用户  1 ios用户 //PushType push类型对应的用户标识类型
                        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String date2 = dateFormat.format(gr.getCreateTime());
                        Map<String, String> parms = new HashMap<>();
                        parms.put("Id", gr.getId().toString());///订单id
                        parms.put("orderCode", gr.getOrderNo());

                        parms.put("createTime", date2);//下单时间

                        parms.put("sound", "refuse.caf");
                         /*   MsgPushUtils.sendtoAndroid("10", parms, sp.getName() + "已拒绝取消定单" + gr.getOrderNo(), sp.getName() + "拒绝订单取消请求", runfastCuser.getAlias());//将发起取消订单请求的用户id 拒绝请求发送给安卓用户
                            MsgPushUtils.sendtoIOS("10", runfastCuser.getAlias(), runfastCuser.getAlias(), 1, "refuse.caf", sp.getName() + "拒绝取消订单请求", sp.getName() + "拒绝取消订单请求");*/
                //        System.out.println(runfastCuser.get(0).getAlias()+"这是用户的");
                        JiGuangPushUtil.push(Role.Predefine.CUSTOMER, 600, runfastCuser.get(0).getAlias(), "你的跑腿订单" + gr.getOrderNo() + "，骑手拒绝了订单取消请求", parms, null);
                        JiGuangPushUtil.push(Role.Predefine.DRIVER, 600, shopper.get(0).getAlias(), "您的跑腿订单" + gr.getOrderNo() + "你已拒绝了用户订单取消请求", parms, null);
               //         System.out.println(shopper.get(0).getAlias()+"这是骑手的");
                    }


                }
                model.put("msg", "拒绝用户取消订单申请");
                model.put("success", false);
            }

        return model;
    }

/*    public static void main(String[] args) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date2 = dateFormat.format(new Date());
        Map<String, String> parms = new HashMap<>();
        parms.put("Id",12+"");///订单id
        parms.put("orderCode", "123456");

        parms.put("createTime", date2);//下单时间

        parms.put("sound", "refuse.caf");
    //   MsgPushUtils.sendtoAndroid("10", parms, "张三 "+ "已拒绝取消定单" +"123456", "张三 "+ "拒绝订单取消请求", "868918031879277");//将发起取消订单请求的用户id 拒绝请求发送给安卓用户
  //      MsgPushUtils.sendToRegistrationId("07136608","张三 ","已拒绝取消定单" +"123456","张三 ","refuse.caf");
   //     JiGuangPushUtil.push(Role.Predefine.CUSTOMER, 600, "862391030653042", "用户您的跑腿订单862391030653042" +"1234567" + "骑手拒绝了订单取消请求", parms, "refuse.caf");
     //   868918031879277
        JiGuangPushUtil.push(Role.Predefine.DRIVER, 600, "868918031879277", "骑手您的跑腿订单868918031879277" + "12345" + "你已拒绝用户订单取消请求", parms, "refuse.caf");

        System.out.println("试试");
    }*/
}